/**
 * Filename: SharePhotoAdapter.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/6/18 15:20
 */
package com.github.postsanf.yinian.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.SnackBarUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.liulishuo.qiniuimageloader.QiniuImageLoader;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class SharePhotoAdapter extends BaseAdapter {

    public static List<String> mSelectedShare = new LinkedList<>();
    public static List<Integer> mSelectedID = new LinkedList<>();
    private LayoutInflater mInflater;
    private Context mContext;
    private Resources mResource;
    private List<String> datas;
    private HashMap<Integer, Bitmap> mBitmaps = new HashMap<>();
    private ImageLoader mImageLoader;
    private int WidthPixels;

    public void setResource(Resources mResource) {
        this.mResource = mResource;
    }

    public SharePhotoAdapter(Context mContext, List<String> datas) {
        WidthPixels = DisplayUtils.getScreenWidthPixels((Activity) mContext);
        mInflater = LayoutInflater.from(mContext);
        this.mContext = mContext;
        this.datas = datas;
        mImageLoader = ImageLoader.getInstance();
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder mViewHolder;
        if (convertView == null) {
            mViewHolder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.yn_item_share_photo, parent, false);
            mViewHolder.mRl = (RelativeLayout) convertView.findViewById(R.id.rl_item_share_photo);
            mViewHolder.mImageView = (SimpleDraweeView) convertView.findViewById(R.id.iv_item_share_photo);
            mViewHolder.mShare_item_select = (ImageButton) convertView.findViewById(R.id.share_photo_item_select);
            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
        }

        final String path = datas.get(position);
        mViewHolder.mImageView.setTag(path);
        mViewHolder.mImageView.setImageResource(R.drawable.pic_null);

        if (mResource != null) {
            mViewHolder.mShare_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("picture_unselected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
        } else {
            mViewHolder.mShare_item_select.setImageResource(R.drawable.picture_unselected);
        }
        String url = new QiniuImageLoader(mContext, path).halfScreenW().formatWebp().createQiniuUrl();
        mImageLoader.displayImage(StringUtils.repaceImgUrl(url), new ImageViewAware(mViewHolder.mImageView, false),
                ImageOptHelper.getImgOptions(), new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        String message = null;
                        switch (failReason.getType()) {     // 获取图片失败类型
                            case IO_ERROR:              // 文件I/O错误
                                message = "文件错误";
                                break;
                            case DECODING_ERROR:        // 解码错误
                                message = "解码错误";
                                break;
                            case NETWORK_DENIED:        // 网络延迟
                                message = "网络延迟";
                                break;
                            case OUT_OF_MEMORY:         // 内存不足
                                message = "内存不足";
                                break;
                            case UNKNOWN:               // 原因不明
                                message = "未知错误";
                                break;
                        }
                        SnackBarUtils.makeShort(view, message).show();
                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        float scale = (float) loadedImage.getHeight() / loadedImage.getWidth();
                        Bitmap resPic = resizeImage(loadedImage, WidthPixels / 2, (int) (scale * WidthPixels / 2));
//                        Bitmap  shoupic = resizeImage(loadedImage,WidthPixels/3, WidthPixels/3);
                        mViewHolder.mImageView.setScaleType(ImageView.ScaleType.CENTER);
                        mViewHolder.mImageView.setImageBitmap(resPic);
                        mBitmaps.put(position, resPic);
                    }
                }, new ImageLoadingProgressListener() {
                    @Override
                    public void onProgressUpdate(String imageUri, View view,
                                                 int current, int total) {
                    }
                });


//        String paths = YNUrlHelper.getSharePhotoUrl(mContext, path);
//        Uri uri = Uri.parse(paths);
//        ImageOptHelper.showSharePhoto(uri, mViewHolder.mImageView, mContext,new BaseControllerListener(){
//            @Override
//            public void onFinalImageSet(String id, Object imageInfo, Animatable animatable){
//                super.onFinalImageSet(id, imageInfo, animatable);
//                mBitmaps.put(position,mViewHolder.mImageView.getDrawingCache());
//            }
//            @Override
//            public void onFailure(String id, Throwable throwable) {
//                super.onFailure(id, throwable);
//            }
//            @Override
//            public void onIntermediateImageFailed(String id, Throwable throwable) {
//                super.onIntermediateImageFailed(id, throwable);
//            }
//        });

        // 设置图片宽高
        int screenWidth = DisplayUtils.getScreenWidthPixels((Activity) mContext);
        int horizontalSpacing = DisplayUtils.dp2px(mContext, 2);
        int itemWidth = (screenWidth - 2 * horizontalSpacing) / 3;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(itemWidth, itemWidth);
        mViewHolder.mImageView.setLayoutParams(params);


        mViewHolder.mShare_item_select.setVisibility(View.VISIBLE);
        mViewHolder.mImageView.setColorFilter(null);
        // 图片选择事件
//        mViewHolder.mShare_item_select.setOnClickListener(new View.OnClickListener() {
//            //选择，则将图片变暗，反之则反之
//            @Override
//            public void onClick(View v) {
//
//            }
//        });
        // 点击图片大图查看
        mViewHolder.mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 已经选择过该图片
                if (mSelectedShare.contains(String.valueOf(position))) {
                    mSelectedShare.remove(String.valueOf(position));
                    if (mResource != null) {
                        mViewHolder.mShare_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("picture_unselected", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                    } else {
                        mViewHolder.mShare_item_select.setImageResource(R.drawable.picture_unselected);
                    }
                    mViewHolder.mImageView.setColorFilter(null);
                } else
                // 未选择该图片
                {
                    if (mBitmaps.get(position) != null) {
                        mSelectedShare.add(String.valueOf(position));
                        if (mResource != null) {
                            mViewHolder.mShare_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("pictures_selected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                        } else {
                            mViewHolder.mShare_item_select.setImageResource(R.drawable.pictures_selected);
                        }
                        mViewHolder.mImageView.setColorFilter(Color.parseColor("#33000000"));
                    }

                }
            }
        });

        // 响应选择效果
        if (mSelectedShare.contains(String.valueOf(position))) {
            if (mResource != null) {
                mViewHolder.mShare_item_select.setImageDrawable(mResource.getDrawable(mResource.getIdentifier("pictures_selected", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
            } else {
                mViewHolder.mShare_item_select.setImageResource(R.drawable.pictures_selected);
            }
            mViewHolder.mImageView.setColorFilter(Color.parseColor("#33000000"));
        }

        return convertView;
    }

    public static class ViewHolder {
        public RelativeLayout mRl;
        public SimpleDraweeView mImageView;
        public ImageButton mShare_item_select;
    }

    public Bitmap getBitmap(int position) {
        if (position <= mBitmaps.size() - 1) {
            return mBitmaps.get(Integer.parseInt(mSelectedShare.get(position)));
        }
        return null;
    }


    //使用Bitmap加Matrix来缩放
    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }
}